package router

import (
	"aqchain/pkg/config"
	"aqchain/pkg/controller"
	"aqchain/pkg/log"
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Router struct {
	router *gin.Engine
	cfg    config.Config
}

func New(cfg config.Config, db *gorm.DB) Router {
	router := gin.Default()
	router.Use(gin.Logger())
	router.Use(cors.Default())

	ctl := controller.New(cfg, db)
	api := router.Group("/api")
	api.POST("/upload", ctl.Upload)
	api.GET("/certificate/:dci", ctl.GetCertificatePDF)
	api.GET("/itemPictures/:dci", ctl.GetItemPictures)

	api.GET("/file/:dci", ctl.GetFile)

	api.GET("/item/:dci", ctl.GetItem)
	api.GET("/items", ctl.GetItems)
	api.GET("/itemEvents", ctl.GetEventItems)

	api.GET("/sale/:dci", ctl.GetSale)
	api.GET("/sales", ctl.GetSales)

	api.GET("/auction/:dci", ctl.GetAuction)
	api.GET("/auctions", ctl.GetAuctions)
	api.GET("/auctionEvents", ctl.GetAuctionEvents)

	api.GET("/license/:dci", ctl.GetLicense)
	api.GET("/licenses", ctl.GetLicenses)
	api.GET("/licenseRecords", ctl.GetLicenseRecords)
	api.GET("/licenseEvents", ctl.GetLicenseEvents)
	//api.GET("/license", ctl.GetLicense)

	api.GET("/trades", ctl.GetTrades)

	api.POST("/account", ctl.CreateAccount)
	api.GET("/account/:address", ctl.GetAccount)
	api.PUT("/account", ctl.UpdateAccount)

	return Router{
		router: router,
		cfg:    cfg,
	}
}

func (r *Router) Run() error {
	log.Logger.Info(fmt.Sprintf("%s:%s", r.cfg.Server.Host, r.cfg.Server.Port))
	return r.router.Run(fmt.Sprintf("%s:%s", r.cfg.Server.Host, r.cfg.Server.Port))
}
